package com.zuma.oci.docker.handler;

import cn.hutool.core.util.StrUtil;
import com.zuma.oci.docker.transport.DockerEngineV2Exception;
import org.apache.hc.core5.http.ClassicHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.function.Consumer;

public class ImageBuildHandler extends IResponseProcessHandler<String> {

    private Consumer<BuildImageLinePrint> tailFunc;

    private String imageId;

    public ImageBuildHandler(Consumer<BuildImageLinePrint> tailFunc) {
        this.tailFunc = tailFunc;
    }

    @Override
    public String process(ClassicHttpResponse response) {
        var errSb = new StringBuilder("");
        if (response.getEntity() != null) {
            try (var is = response.getEntity().getContent(); var reader = new BufferedReader(new InputStreamReader(is))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    var lineResult = BuildImageLinePrint.build(line);
                    if (StrUtil.isNotBlank(lineResult.getStream())) {
                        var stream = lineResult.getStream();
                        if (imageId == null && stream.startsWith("Successfully built")) {
                            imageId = stream.substring(stream.lastIndexOf(' ') + 1).trim();
                        }
                    }
                    if (StrUtil.isNotBlank(lineResult.getError())) {
                        errSb.append(lineResult.getError()).append("\n");
                    }
                    // 打印消息
                    if (tailFunc != null) {
                        tailFunc.accept(lineResult);
                    }
                }
            } catch (IOException e) {
                throw new DockerEngineV2Exception(this.getHost(), this.getUrl(), response.getCode(), response.getReasonPhrase(), e.getMessage());
            }
        }
        int statusCode = response.getCode();
        if (statusCode >= 400 && statusCode <= 500) {
            throw new DockerEngineV2Exception(this.getHost(), this.getUrl(), statusCode, response.getReasonPhrase(), errSb.toString());
        } else if (imageId == null) {
            throw new DockerEngineV2Exception(this.getHost(), this.getUrl(), statusCode, response.getReasonPhrase(), errSb.toString());
        }
        return imageId;
    }
}
